<?php
namespace Foxframe;
use DoctrineExtensions\Paginate\Paginate;

class Paginator
{
	public $actualPage	= 1;
	public $maxResults	= 10;
	public $link;
	public $firstResult;
	public $totalResult;
	public $query;

	public function __construct($query, $actualPage = 1, $maxResults = 10, $link)
	{
		if (!is_null($actualPage))
			$this->actualPage	= $actualPage;
		if (!is_null($maxResults))
			$this->maxResults	= $maxResults;
		$this->link			= $link;

		if ($this->actualPage == 1)
			$this->firstResult	= 0;
		else
			$this->firstResult	= ($this->maxResults * $this->actualPage) - $this->maxResults;

		$this->totalResult	= Paginate::count($query);
		$this->query		= $query->setFirstResult($this->firstResult)->setMaxResults($this->maxResults);
		return $this;
	}

	public function pagination()
	{
		if ($this->totalResult == 0)
			return null;
		$totalPages	= ceil($this->totalResult / $this->maxResults);
		$proxima	= $this->actualPage + 1;
		$anterior	= $this->actualPage - 1;
		$paginator	= "<div class='pagination btn-group fRight'>";
		if ($this->actualPage == 1)
		{
			$paginator	.= "<a class='btn icon-fast-backward disabled'></a></li>";
			$paginator	.= "<a class='btn icon-step-backward disabled'></a></li>";
		}
		else
		{
			$paginator	.= "<a class='btn icon-fast-backward' href='{$this->link}1'></a></li>";
			$paginator	.= "<a class='btn icon-step-backward' href='{$this->link}{$anterior}'></a></li>";
		}

		$pag	= $this->actualPage - 2 < 1 ? 1 : $this->actualPage - 2;
		for ($j = 0; $j < 5 && $pag <= $totalPages; $j++)
		{
			if ($pag == $this->actualPage)
				$paginator	.= "<a class='btn btn-inverse' href='{$this->link}{$pag}'>{$pag}</a>";
			else
				$paginator	.= "<a class='btn' href='{$this->link}{$pag}'>{$pag}</a>";
			$pag++;
		}

		if ($this->actualPage == $totalPages)
		{
			$paginator	.= "<a class='btn icon-step-forward disabled'  href='{$this->link}{$proxima}'></a>";
			$paginator	.= "<a class='btn icon-fast-forward disabled'  href='{$this->link}{$totalPages}'></a>";
		}
		else
		{
			$paginator	.= "<a class='btn icon-step-forward'  href='{$this->link}{$proxima}'></a>";
			$paginator	.= "<a class='btn icon-fast-forward'  href='{$this->link}{$totalPages}'></a>";
		}
		$paginator	.= "</div>";

		return $paginator;
	}
}